from onlineuser.models import Online
import logging
import datetime
from google.appengine.ext import db
from google.appengine.api import memcache

def notify_visit(user,ip):
    #if user calls logout

    online=None
    if user.is_authenticated():
        key="online_%s"%user.key()
        #q_online=Online.all().filter('user=' ,key)
        #online=q_online.get()
        online = Online.get_by_key_name(key)
        if online is None:
            online=Online(key_name=key,ip=ip,user=user)
            online.put()
            return
    else:
        key="online_%s"%ip
        online=Online.get_by_key_name(key)
        if online is None:
            online=Online(key_name=key,ip=ip)
            online.put()
            return
        
    #visited before
    now=datetime.datetime.now()
    span = datetime.timedelta(seconds=60*1)
    spot=now-span
    
    #do not refresh in 5 mins . 
    #not need to refresh for img all.its one req in fact
    #logging.log(logging.INFO,"xxx")
    if online.updated_on < spot:
        #logging.log(logging.INFO,"put")
        online.put()
    #else:
        #logging.log(logging.INFO,"not put")


class OnlineUserMiddleware:
    def process_request(self, request):
        #ip = request.META['HTTP_X_FORWARDED_FOR'] 
        ip = request.META['REMOTE_ADDR']
        #logging.log(logging.INFO,ip)
        user = request.user
        current_path=request.META['PATH_INFO']
        
        if current_path == "/account/logout/":
            key=""            
            logging.log(logging.INFO,"logging out :%s"%current_path)
            if user.is_authenticated():
                key="online_%s"%user.key()
            else:
                key="online_%s"%ip
            #online=db.get(key)
            online=Online.get_by_key_name(key)
            online.delete()
            memcache.delete(key)
            #logging.log(logging.INFO,"online:%s!!!"%str(online))
            return
        
        #return
        notify_visit(user,ip)
        return
    